package bTree.LeetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 组合总和2 {
    List<List<Integer>>res=new ArrayList<>();
    List<Integer>temp=new ArrayList<>();
    int sum=0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates,target,0);
        return res;
    }

    private void backtracking(int[] candidates, int target, int startindex) {
        if(sum==target){
            res.add(new ArrayList<>(temp));
            return;
        }
        if(sum>target){
            return;
        }

        for (int i=startindex;i<candidates.length;i++){
            if(i>startindex&&candidates[i]==candidates[i-1]){
                continue;//同一层的话直接continue,i>startindex两个妙点，第一个，保证i>0,不会
                //越界。第二个是保证了纵向便利的不会受影响，因为纵向的相等
            }
            sum+=candidates[i];
            temp.add(candidates[i]);
            backtracking(candidates,target,i+1);
            sum-=candidates[i];
            temp.remove(temp.size()-1);
        }
    }
}